from calm.sensors.directionSensor import DirectionSensor
from system.vec2 import Vec2
from system.gameServer import gameServer

class PicDirectionSensor(DirectionSensor):
    def __init__(self, controller, vars, numSlices = 8):
        self.allowFilled = False
        
        DirectionSensor.__init__(self, controller, vars, numSlices)
        
        self.server = self.agent.searchAncestors("type","calm.calmServer")
        assert self.server, "picDirectionSensor can't find calmServer"
        assert self.server.evaluators.has_key("calm.evaluators.picEvaluator"), "picDirectionSensor can't find picEvaluator"
        self.picEvaluator = self.server.evaluators['calm.evaluators.picEvaluator']
        
    def acceptBits(self, bits):
        pos = Vec2(self.agent.getVar("pos"))
        
        minDist = None
        for pixel in self.picEvaluator.pixels:
            if self.allowFilled or pixel not in self.picEvaluator.filledPixels:
                #print self.picEvaluator.w, self.picEvaluator.h
                x = (pixel[0] + 0.5) / float(self.picEvaluator.w) * float(gameServer.screenw)
                y = (pixel[1] + 0.5) / float(self.picEvaluator.h) * float(gameServer.screenh)
                dist = (Vec2(x,y) - pos).length()
                if not minDist or dist < minDist:
                    minDist = dist
                    self.point = (x,y)
                
        #print self.agent.getVar("name"), "look at", self.point
        return DirectionSensor.acceptBits(self,bits)
                
            
